import React, { Component } from 'react'
import PropTypes from 'prop-types' 
import { farmLandSave, findSeasonLists, getLocationByLonLat } from '../utils/Api.js'
import {  addFeature } from '_redux/actions/userFeature'
import { getMyField } from '_redux/actions/myField'
import ol from 'openlayers'
import { connect } from 'react-redux'
import 'css/index/common/createFiled.scss'
import 'css/map/popup1.scss'
import { setFeature } from '_redux/actions/feature'

class CreateField extends Component {
  constructor(props) {
    super(props)
    this.state = {
      position: '',
      addresss: '',
      status: '0',
      seasons: [],
      season: '',
      saving: false,
      name: ''
    }
  }
  componentDidMount() {
    this.overlay = new ol.Overlay({
      element: document.querySelector('.ol-popup'),
      autoPan: true,
      autoPanAnimation: {
        duration: 250
      },
      stopEvent: true
    })
    const { coord: coordinate, map: {map} } = this.props
    map.addOverlay(this.overlay)
    this.load()
    this.closer.onclick = this.closeClick
    this.clear.onclick = this.clearHandler.bind(this)
        
        

    // var geoCoder = new BMap.Geocoder()

    // var pt = ol.proj.transform(coordinate, 'EPSG:3857', 'EPSG:4326')
    // const self = this
    // geoCoder.getLocation(new BMap.Point(...pt), (rs) => {
    //   const { province = '', city = '', distract ='' } = rs.addressComponents
    //   self.setState({
    //     position: `${province} ${city} ${distract}`
    //   })
    // })
    var pt = ol.proj.transform(coordinate, 'EPSG:3857', 'EPSG:4326')
    getLocationByLonLat({
      latitude: pt[1],
      longitude: pt[0]
    })
      .then(({ msg, result: { countries = '', province = '', city = '', county = '' } }) => {
        if (msg === '200') {
          this.setState({
            position: `${countries} ${province} ${city} ${county}`,
            address: `${countries},${province},${city},${county}`
          })
        }
      })
    findSeasonLists()
      .then(({msg, result}) => {
        if(msg === '200') {
          const seasons = result.map(r => ({
            value: r.id,
            label: r.name
          }))
          this.setState({
            seasons,
            season: seasons[seasons.length-1].value
          })
        }
      }) 
  }
  clearHandler = (e) => {
    e.preventDefault()
    this.props.setDefault()
    this.props.sourceClear()
  }
  componentDidUpdate(prevProps, preState) {
    if (!this.state.saving) {
      !this.clear.onclick && (this.clear.onclick = this.clearHandler.bind(this))
    }
    const { coord: coordinate } = this.props
    this.overlay.setPosition(coordinate)
    if (!coordinate) {
      if (!!this.state.position) {
        this.setState({
          position: '',
          address: ''
        })
      }
      return
    }
    if ((!prevProps.coord && coordinate) || coordinate[0] !== prevProps.coord[0] 
      || coordinate[1] !== prevProps.coord[1]) {
      var pt = ol.proj.transform(coordinate, 'EPSG:3857', 'EPSG:4326')
      getLocationByLonLat({
        latitude: pt[1],
        longitude: pt[0]
      })
        .then(({ msg, result: { countries = '', province = '', city = '', county = ''} }) => {
          if (msg === '200') {
            this.setState({
              position: `${countries} ${province} ${city} ${county}`,
              address: `${countries},${province},${city},${county}`
            })
          }
        })
    }
    
       
  }
  componentWillUnmount() {
    this.overlay = null
  }
  load = () => {
    const { coord: coordinate } = this.props
    this.overlay.setPosition(coordinate)
  }
  closeClick = (e) => {
    e.preventDefault()
    this.overlay.setPosition(undefined)
    
    this.closer.blur()
    this.props.setInitial()
  }
  changeInput = (e) => {
    e.preventDefault()
    this.setState({
      name: e.target.value
    })
  }
  submitHandle = (e) => {
    const { name, address, season, status } = this.state
    const { area } = this.props
    e.preventDefault()
    if (!name.trim()) {
      alert('地的名称不为空')
      return
    }
    const { feature: { feature }, map: { map } } = this.props
    // 圈地
    const farmLandInfo = {
      name,
      geom: (new ol.format.GeoJSON()).writeGeometry(feature.getGeometry(), {
        dataProjection: 'EPSG:4326',
        featureProjection: 'EPSG:3857'
      }),
      address,
      season,
      status
    }
    this.setState({
      saving: true,
    })
    const fd = new FormData()
    fd.append('farmLandInfo', JSON.stringify(farmLandInfo))
    const vector = map
      .getLayers()
      .getArray()
      .filter(lyr => lyr.get('id') === 'vector')[0]
    farmLandSave(fd).then(({ msg, result: id }) => {
      if (msg === '200') {
        this.props.feature.feature.set('address', address)
        this.props.feature.feature.set('area', area)
        this.props.feature.feature.set('name', name)
        this.props.feature.feature.set('status', '1')
        this.props.feature.feature.set('growth_status', status)
        this.props.feature.feature.set('season_id', season)
        this.props.feature.feature.setId(id)
        this.props.setFeature({
          address,
          name,
          id,
          growthStatus: status
                    
        })
        this.props.setDefault()
        this.props.drawText()
        this.setState({
          name: ''
        })
        this.props.sourceClear()
        this.props.getMyField()
        vector.getSource().addFeature(this.props.feature.feature)
        vector.getSource().refresh()
        this.props.addFeature(this.props.feature.feature)
        this.props.refresh(this.props.feature.feature)
        map.getLayers().getArray().forEach(lyr => {
          if (lyr.get('_id') === 'kml') {
            const feature = lyr.getSource().getFeatures()[0]
            lyr.getSource().removeFeature(feature)
           
          }
        })
        
      } else if (data.msg === '209') {
        this.setState({
          name: ''
        })
        this.props.setDefault()  
        alert(data.result+ ' ，请重绘。。。')
      }
      this.setState({
        saving: false
      })
    }).catch(err=> {
      this.setState({
        saving: false
      })
    })
    

  }
  seasonChange = (e) => {
    this.setState({
      season: e.target.value
    })
  }
  statusChange = (e) => {
    this.setState({
      status: e.target.value
    })
  }
  nameChange = ({ target: { value }}) => {
    this.setState({
      name: value
    })
  }
  render() {
    const { area } = this.props
    const { position, status, name } = this.state
    return (
      <div className="ol-popup">
        <a href="#" id='close' className="ol-popup-closer"
          ref={closer => this.closer = closer}></a>
        <div className="popup-content">
          <form onSubmit={this.submitHandle}>
            <input  
              required 
              type="text" 
              className='ppfix post email' 
              name='name'
              value={name}
              onChange={this.nameChange}
            />
            <div>
              <label>位置：</label>
              <span>{position}</span>
            </div>
            <div>面积：{area.acre} 亩 / {area.hectare} 公顷</div>
            <div className='season-status'>
              <div>
                <label>种植季节：</label>
                <select value={this.state.season} onChange={this.seasonChange}>
                  {
                    this.state.seasons.map(season => 
                      <option
                        key={season.value}
                        value={season.value}>
                        {season.label}
                      </option>)
                  }
                </select> 
              </div>
              <div>
                <label>状态：</label>
                <select value={status} onChange={this.statusChange}>
                  {
                    // 0:闲置;1:优;2:中;3:差
                    [{
                      label: '优',
                      value: '0'
                    },
                    {
                      label: '良',
                      value: '1'
                    },
                    {
                      label: '差',
                      value: '2'
                    },
                    {
                      label: '闲',
                      value: '3'
                    },
                    {
                      label: '弃',
                      value: '4'
                    },
                    {
                      label: '不选择',
                      value: '5'
                    }].map(status => 
                      <option
                        key={status.value}
                        value={status.value}>
                        {status.label}
                      </option>)
                  }
                </select>
              </div>
            </div>
            
            <div style={{display: 'flex', justifyContent: 'space-between'}}>
              <button className='button blue' disabled={this.state.saving}>{!this.state.saving ? '保存' : '保存中'}</button>                   
              {!this.state.saving 
                && <button type='button' className='button blue' ref={clear => this.clear = clear} >清除</button>}
            </div>
          </form>
        </div>
      </div>
            
    )
  }
  
}

CreateField.propTypes = {
  area: PropTypes.object,
  setFeature: PropTypes.func,
  geom: PropTypes.string,
  map: PropTypes.object,
  coord: PropTypes.array,
  drawText: PropTypes.func,
  feature: PropTypes.object,
  setDefault: PropTypes.func,
  setInitial: PropTypes.func,
  sourceClear: PropTypes.func,
  source: PropTypes.object,
  refresh: PropTypes.func,
  addFeature: PropTypes.func,
  getMyField: PropTypes.func,
}
const mapStateToProps = (state) => {
  return {
    map: state.map,
    feature: state.feature,
    source: state.source
  }
}
const mapDispathToProps = (dispatch) => {
  return {
    setFeature: (feature) => {
      dispatch(setFeature(feature))
    },
    refresh: (feature) => {
      dispatch({ type: 'refresh',  feature})
    },
    addFeature: (feature) => {
      dispatch(addFeature(feature))
    },
    getMyField: function () {
      dispatch(getMyField())
    }
  }
}
export default connect(mapStateToProps, mapDispathToProps)(CreateField)